package com.luom.fsp.utils;

import com.luom.fsp.model.entity.User;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;
import lombok.extern.slf4j.Slf4j;
import com.luom.fsp.exception.BusinessException;
import com.luom.fsp.common.ErrorCode;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JwtUtil {
    private static final String SIGN_KEY = "luom";
    private static final long EXPIRE_TIME = 1000 * 3600;
    private static final long EXPIRE_TIME_TIME = System.currentTimeMillis() + EXPIRE_TIME;

    // 生成 token
    public static String createToken(User user) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        claims.put("userRole", user.getUserRole());
        if (user.getUserName()!=null){
            claims.put("userName", user.getUserName());
        }
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE_TIME_TIME))
                .signWith(SignatureAlgorithm.HS256, SIGN_KEY)
                .compact();
    }

    //解析 token
    public static Map<String, Object> parseToken(String token) {
        if (token == null)
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        try {
            Map<String, Object> claims = Jwts.parser()
                    .setSigningKey(SIGN_KEY)
                    .parseClaimsJws(token)
                    .getBody();
            return claims;
        } catch (SignatureException | ExpiredJwtException | io.jsonwebtoken.MalformedJwtException | io.jsonwebtoken.UnsupportedJwtException | IllegalArgumentException e) {

            throw new BusinessException(ErrorCode.INVALID_JWT_ERROR);
        }
    }

    public static String getToken(HttpServletRequest request) {
        // 检查 request 是否为空
        if (request == null) {
            log.error("HttpServletRequest 对象为空，无法获取 token");
            return null;
        }
        String token = null;
        try {
            // 尝试从请求头获取 token
            token = request.getHeader("Authorization");
            if (token == null)  {
                // 若请求头中没有，尝试从请求参数获取
                token = request.getParameter("Authorization");
            }
        } catch (Exception e) {
            // 记录异常信息
            log.error("获取 token 时出现异常", e);
        }
        if (token != null && token.trim().isEmpty()) {
            token = null;
        }
        return token;
    }
}
